<template>
  <div>
    <!-- 内容主体区域 -->
    <dtDialog title="修改数据范围" :visible.sync="visible" :is-loading="loading" @closeDialog="handleClose()" @comfirmBtn="onSubmit()">
      <el-form ref="form" slot="content" :model="formData" label-width="72px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" autocomplete="off" placeholder="请输入角色名称" disabled />
        </el-form-item>
        <el-form-item label="数据范围" prop="dataScopeType">
          <el-radio-group v-model="formData.dataScopeType">
            <el-radio
              v-for="dict in dict.type.dataScopeType"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row>
          <el-tree
            v-if="formData.dataScopeType == 40"
            ref="tree"
            class="tree"
            :data="formData.tree"
            :props="defaultProps"
            show-checkbox
            :load="load"
            lazy
            node-key="id"
            :default-checked-keys="checkedKeys"
            :default-expand-all="false"
            :check-on-click-node="true"
            :expand-on-click-node="false"
            :check-strictly="true"
            @check="handleNodeCheck"
          />
        </el-row>
      </el-form>
    </dtDialog>
  </div>
</template>
<script>
import roleApi from '@/framework/api/permissionCenter/roleManage'
export default {
  name: 'RoleDataScope',
  dicts: ['dataScopeType'],
  data() {
    return {
      visible: false,
      loading: false,
      grantOrgIdList: [],
      checkedKeys: [],
      formData: {
        roleName: '',
        dataScopeType: ''
      },
      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'name'
      },
      nodeTree: {}
    }
  },
  methods: {
    async openDataScope(id) {
      this.visible = true
      const res = await roleApi.getRoleById(id)
      // 改为懒加载
      const resBos = await roleApi.roleBindOrgScopeLazyAntdv({ roleId: id, orgId: 0 })
      this.formData = {
        'roleName': res.data.roleName,
        'dataScopeType': res.data.dataScopeType,
        'roleId': res.data.roleId,
        'tree': resBos.data
      }
      this.getRoleBindOrgScope(resBos.data, res.data)
    },
    // 获取数据范围列表
    getRoleBindOrgScope(data, detailData) {
      this.checkedKeys = detailData.dataScopeOrganizationIds
      this.grantOrgIdList = this.checkedKeys
    },
    async handleNodeCheck(data) {
      const list = []
      const orgList = this.$refs.tree.getCheckedNodes()
      for (let i = 0; i < orgList.length; i++) {
        list.push(orgList[i].id)
      }
      this.grantOrgIdList = list
      const node = this.$refs.tree.getNode(data)
      if (node.checked || node.data.disabled) { // 判断是否禁用子节点--禁用
        await this.$nextTick()
        this.dealTreeData(node, !node.data.disabled)
      } else {
        this.dealTreeData(node, false)
      }
    },
    // 关闭对话框触发
    handleClose() {
      // 清空数据关闭页面
      this.formData = {}
      this.$refs['form'].resetFields()
    },
    async onSubmit() {
      this.loading = true
      if (this.formData.dataScopeType === 40 && (!this.grantOrgIdList || (this.grantOrgIdList && this.grantOrgIdList.length === 0))) {
        this.$message({
          type: 'error',
          message: '请选择部门'
        })
        this.loading = false
        return false
      }
      const data = {
        'dataScopeType': this.formData.dataScopeType,
        'grantOrgIdList': this.grantOrgIdList,
        'roleId': this.formData.roleId
      }
      try {
        const res = await roleApi.grantDataScope(data)
        if (res.code === '00000') {
          this.$message({
            type: 'success',
            message: '修改成功'
          })
          this.$parent.getList()
          this.visible = false
        }
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },
    load(tree, resolve) {
      let id = ''
      if (!tree.data || tree.data.length === 0) {
        id = 0
      } else if (tree.data.length > 0) {
        resolve(tree.data)
        return
      } else {
        id = tree.data.id
      }
      roleApi.roleBindOrgScopeLazyAntdv({ roleId: this.formData.roleId, orgId: id }).then((res) => {
        resolve(res.data)
      })
      // this.nodeTree = tree
      if (tree.checked || tree.data.disabled) { // 判断是否禁用子节点
        this.$nextTick()
        this.dealTreeData(tree, true)
      }
    },
    // 递归处理treeData
    dealTreeData(node, status) {
      setTimeout(() => {
        node.childNodes.forEach(res => {
          this.setDisabledTreeData(node.childNodes, res.id, status)
          if (res.childNodes && res.childNodes.length > 0) {
            this.dealTreeData(res, status)
          }
        })
      }, 200)
    },
    /**
     * 禁用节点
     * @param {*} data
     * @param {*} id 值不为undefined设置禁用节点；反之则清除禁用节点
     * @param {*} status true 禁用  false 不禁用
     */
    setDisabledTreeData(data, id, status) {
      // const val = id !== undefined
      data.forEach((item) => { // 遍历整个树 数据
        this.$set(item.data, 'disabled', status)
        status && this.$refs.tree.setChecked(item, false)
      })
    }
  }
}
</script>

<style scoped>

</style>
